package com.wing.product.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.dict.model.entity.DictLabel;
import com.wing.dict.service.DictLabelService;
import com.wing.platform.feign.PlatformClient;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.request.ProductTypeForm;
import com.wing.product.model.response.ProductTypeVO;
import com.wing.product.service.ProductTypeService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.Role;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.ProductTypeExcelIn;
import com.wing.web.excel.UserExcelIn;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-产品类型管理", tags = "#/product/productType/productTypeSystem")
@RestController("productTypeController")
@RequestMapping("product/admin/productType")
public class ProductTypeController {

    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private PlatformClient platformClient;

    @Autowired
    private DictLabelService dictLabelService;

    @Autowired
    private UserClient userClient;

    @ApiOperation(value = "查询所有产品类型", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "code", value = "编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProductTypeVO> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "desc") String order
            , String name
            , String code
            , String materialNature
            , String parentId
            , @RequestParam(defaultValue = "enterprise") ProductType.DataSourceType dataSourceType
            , @RequestParam(required = false, name = "requestType") String requestType) {
        Page<ProductTypeVO> pg = new Page<>(page, limit);
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order", StrUtil.toUnderlineCase(order));
        paramMap.put("name", name);
        paramMap.put("code", code);
        paramMap.put("parentId", parentId);
        paramMap.put("materialNature", materialNature);
        if (dataSourceType != null) {
            paramMap.put("dataSourceType", dataSourceType.getValue());
        }
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        paramMap.put("databaseUser", databaseUser);

        IPage<ProductTypeVO> list = productTypeService.pageList4app(pg, paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加产品类型", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ProductTypeForm.Add.class) ProductTypeForm productTypeForm) {
        if (productTypeService.add(productTypeForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "启用产品类型", notes = "启用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/enable")
    public JsonResult enable(@Validated(ProductTypeForm.Add.class) ProductTypeForm productTypeForm) {
        ProductType productType = new ProductType();
        productType.setId(productTypeForm.getId());
        productType.setIsDeleted(true);
        if (productTypeService.updateById(productType)) {
            return JsonResult.success("启用成功");
        }
        return JsonResult.fail("启用失败");
    }

    @ApiOperation(value = "停用产品类型", notes = "停用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/disable")
    public JsonResult disable(@Validated(ProductTypeForm.Add.class) ProductTypeForm productTypeForm) {
        ProductType productType = new ProductType();
        productType.setId(productTypeForm.getId());
        productType.setIsDeleted(false);
        if (productTypeService.updateById(productType)) {
            return JsonResult.success("停用成功");
        }
        return JsonResult.fail("停用失败");
    }


    @ApiOperation(value = "修改产品类型", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ProductTypeForm.Update.class) ProductTypeForm productTypeForm) {
        ProductType productType = productTypeService.getById(productTypeForm.getId());
        if (productType == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductType.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productTypeForm, productType, copyOptions);
        if (productTypeService.updateById(productType)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除产品类型", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productTypeId", value = "产品类型id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long productTypeId) {
        if (productTypeService.removeById(productTypeId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @GetMapping("/getProductTypeVoById")
    public JsonResult<ProductTypeVO> getProductTypeVoById(Long productTypeId) {
        ProductTypeVO productTypeVO = productTypeService.get4appById(productTypeId);
        return JsonResult.success(productTypeVO);
    }

    @GetMapping("/getProductTypeVOAll")
    public JsonResult getProductTypeVOAll() {
        QueryWrapper<ProductType> wrapper = new QueryWrapper<>();
        wrapper.eq("data_source_type", ProductType.DataSourceType.enterprise.getValue());
        List<ProductType> productType = productTypeService.list(wrapper);
        return JsonResult.success(productType);
    }

    @GetMapping("/getProductTypeByType")
    public JsonResult getProductTypeByType(Integer type) {
        QueryWrapper<ProductType> wrapper = new QueryWrapper<>();
        if (null != type) {
            wrapper.eq("type", type);
        }
        wrapper.eq("data_source_type", ProductType.DataSourceType.enterprise.getValue());
        List<ProductType> productType = productTypeService.list(wrapper);
        return JsonResult.success(productType);
    }

    /**
     * 查询所有产品类型
     */
    @GetMapping("/getAllKnife")
    public JsonResult getAll() {
        QueryWrapper<ProductType> wrapper = new QueryWrapper<>();
        wrapper.eq("type", "5");
        wrapper.eq("data_source_type", ProductType.DataSourceType.enterprise.getValue());
        List<ProductType> list = productTypeService.list(wrapper);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "查询平台的所有产品类型", notes = "查询平台的所有产品类型")
    @GetMapping("/platformProductTypeList")
    public JsonResult platformProductTypeList() {
        return platformClient.platformProductTypeList();
    }

    @ApiOperation(value = "检查唯一性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "Long", paramType = "query")
    })
    @GetMapping("/isOnly")
    public JsonResult isOnly(@RequestParam(name = "name", required = false) String name,
                             @RequestParam(name = "id", required = false) Long id) {
        QueryWrapper<ProductType> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.eq("name", name);
        }
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        int count = productTypeService.count(queryWrapper);
        return JsonResult.success(count == 0);
    }

    @ApiOperation(value = "获取所有父级类别")
    @GetMapping("/getTreeData")
    public JsonResult getTreeData(
            @RequestParam(name = "productTypeId", required = false) Long productTypeId,
            @RequestParam(name = "materialNatureList[]", required = false) List<Long> materialNatureList) {
        return productTypeService.getTreeData(productTypeId, materialNatureList);
    }


    @ApiOperation(value = "获取所有类别")
    @GetMapping("/getAllTreeData")
    public JsonResult getAllTreeData(
            @RequestParam(name = "productTypeId", required = false) Long productTypeId,
            @RequestParam(name = "materialNatureList[]", required = false) List<Long> materialNatureList) {
        return productTypeService.getAllTreeData(productTypeId, materialNatureList);
    }

    @ApiOperation(value = "物料类别树-只能选最后一级")
    @GetMapping("/getTreeDataForLast")
    public JsonResult getTreeDataForLast(
            @RequestParam(name = "productTypeId", required = false) Long productTypeId,
            @RequestParam(name = "materialNatureList[]", required = false) List<Long> materialNatureList) {
        return productTypeService.getTreeDataForLast(productTypeId, materialNatureList);
    }

    @ApiOperation(value = "获取当前类别")
    @GetMapping("/get")
    public JsonResult get(Long id) {
        return JsonResult.success(productTypeService.getById(id));
    }

    @ApiOperation(value = "查询条数")
    @GetMapping("/getCount")
    public JsonResult getCount(Long productTypeId) {
        return JsonResult.success(productTypeService.getProductTypeCount(productTypeId));
    }


    /**
     * 下载物资类别录入excel模板
     */
    @ApiOperation(value = "下载物资类别录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"类别编码", "类别名称", "上级类别", "是否终极分类", "是否一物一码", "是否有质保期", "是否先进先出", "类别性质", "类别维护部门", "排序"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();
        //是否终极分类
        String[] data = new String[2];
        data[0] = "是";
        data[1] = "否";
        indexArr.add("3");
        downData.add(data);
        //是否一物一码
        String[] data1 = new String[2];
        data1[0] = "是";
        data1[1] = "否";
        indexArr.add("4");
        downData.add(data1);
        //是否有质保期
        String[] data2 = new String[2];
        data2[0] = "是";
        data2[1] = "否";
        indexArr.add("5");
        downData.add(data2);
        //是否先进先出
        String[] data3 = new String[2];
        data3[0] = "是";
        data3[1] = "否";
        indexArr.add("6");
        downData.add(data3);
        //类别性质
        QueryWrapper<DictLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type", "sys_product_type_nature");
        List<DictLabel> dictLabelList = dictLabelService.list(queryWrapper);
        String[] data4 = new String[dictLabelList.size()];
        for (int i = 0; i < dictLabelList.size(); i++) {
            data4[i] = dictLabelList.get(i).getLabelName();
        }
        indexArr.add("7");
        downData.add(data4);
        //维护部门
        List<Role> roleList = userClient.getRoleDepartment();
        String[] data5 = new String[roleList.size()];
        for (int i = 0; i < roleList.size(); i++) {
            data5[i] = roleList.get(i).getName();
        }
        indexArr.add("8");
        downData.add(data5);
        DownExcelUtil.createExcelTemplate(response, request, "物资类别导入模板", Arrays.asList(headerArr), downData, indexArr);
    }

    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<ProductTypeExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<ProductTypeExcelIn> list = reader.read(is, ProductTypeExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            productTypeService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

}
